/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-08-06
*/
package com.rzico.order.service;

import com.alibaba.fastjson.JSON;
import com.rzico.account.service.PointService;
import com.rzico.base.BaseMapper;
import com.rzico.base.impl.BaseServiceImpl;
import com.rzico.basics.entity.BomItem;
import com.rzico.basics.entity.Member;
import com.rzico.basics.entity.Product;
import com.rzico.basics.entity.Promotion;
import com.rzico.basics.service.BomItemService;
import com.rzico.basics.service.MemberService;
import com.rzico.basics.service.MsgService;
import com.rzico.basics.service.ProductService;
import com.rzico.order.entity.*;
import com.rzico.order.enumx.OrderLogTypeEnum;
import com.rzico.order.enumx.OrderStatusEnum;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import com.rzico.order.mapper.GiftCardMapper;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * <pre>
 * 礼品卡业务类
 * </pre>
 *
 * @author Rzico Boot
 * @version 1.0
 */
@Service
@Slf4j
public class GiftCardService extends BaseServiceImpl<GiftCard, String> {

    @Autowired
    private GiftCardMapper giftCardMapper;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private OrderService orderService;

    @Autowired @Lazy
    private MsgService msgService;

    @Autowired
    private PointService pointService;

    @Autowired
    private OrderLogService orderLogService;

    @Autowired
    private ProductService productService;

    @Autowired
    private MemberService memberService;

    @Override
    public BaseMapper<GiftCard, String> getMapper() {
        return giftCardMapper;
    }

    private void initOrder(Order order){
        if (order.getIsFirst()==null) {
            order.setIsFirst(false);
        }
        if (order.getIsDistribution()==null) {
            order.setIsDistribution(false);
        }
        //若空，默认0线上结算
        if (null == order.getAmountPaid()){
            order.setAmountPaid(BigDecimal.ZERO);
        }
        if (null == order.getAmountPayable()){
            order.setAmountPayable(BigDecimal.ZERO);
        }
        if (null == order.getFee()){
            order.setFee(BigDecimal.ZERO);
        }
        if (null == order.getFreight()){
            order.setFreight(BigDecimal.ZERO);
        }
        if (null == order.getLevelFreight()){
            order.setLevelFreight(BigDecimal.ZERO);
        }
        if (null == order.getOffsetAmount()){
            order.setOffsetAmount(BigDecimal.ZERO);
        }
        if (null == order.getPoint()){
            order.setPoint(0L);
        }
        if (null == order.getDiscount()){
            order.setDiscount(BigDecimal.ZERO);
        }
        if (null == order.getSubPrice()){
            order.setSubPrice(BigDecimal.ZERO);
        }
        if (null == order.getSubQuantity()){
            order.setSubQuantity(BigDecimal.ZERO);
        }
        if (null == order.getCouponCodeId()){
            order.setCouponCodeId(0L);
        }
        if (null == order.getMemberId()){
            order.setMemberId(0L);
        }
        if (null == order.getShippingMethod()){
            order.setShippingMethod(0);
        }
        if (null == order.getLat()){
            order.setLat(0d);
        }
        if (null == order.getLng()){
            order.setLng(0d);
        }

        if (null == order.getTax()){
            order.setTax(new BigDecimal(17));
        }
        if (null == order.getShopId()){
            order.setShopId(0L);
        }

        if (null == order.getOrderMethod()){
            order.setOrderMethod(0);
        }

        if (null == order.getPromoterId1()){
            order.setPromoterId1(0L);
        }
        if (null == order.getPromoterId2()){
            order.setPromoterId2(0L);
        }

        if (null == order.getRebate1()){
            order.setRebate1(BigDecimal.ZERO);
        }
        if (null == order.getRebate2()){
            order.setRebate2(BigDecimal.ZERO);
        }

        if (null == order.getTaxType()){
            order.setTaxType(0);
        }
        if (null == order.getInvoiced()){
            order.setInvoiced(false);
        }
        if (null == order.getOrderStatus()){
            order.setOrderStatus(0);
        }
        if (null == order.getPaymentStatus()){
            order.setPaymentStatus(0);
        }
        if (null == order.getShippingStatus()){
            order.setShippingStatus(0);
        }
        if (null == order.getOrderDate()){
            order.setOrderDate(DateUtils.truncate(new Date(), Calendar.DATE));
        } else {
            order.setOrderDate(DateUtils.truncate(order.getOrderDate(),Calendar.DATE));
        }
    }


    public Order build(GiftCard giftCard) {

        Order order = new Order();
        initOrder(order);
        if (giftCard.getReceiverId()==null) {
            //自用
            order.setMemberId(giftCard.getMemberId());
        } else {
            order.setMemberId(giftCard.getReceiverId());
        }

        order.setGiftCardId(giftCard.getId());

        Member member = memberService.findById(order.getMemberId());

        order.setCompanyId(member.getCompanyId());
        List<OrderItem> orderItems = new ArrayList<>();

        if (giftCard.getType().equals(0)) {
                    OrderItem orderItem = new OrderItem();
                    Product product = productService.selectByPrimaryKey(giftCard.getProductId());
                    orderItem.setSubType(product.getSubType());
                    orderItem.setThumbnail(product.getThumbnail());
                    orderItem.setName(product.getName());
                    orderItem.setUnit(product.getUnit());
                    orderItem.setSn(product.getSn());
                    orderItem.setSpec(product.getSpec());
                    orderItem.setCost(product.getCost());
                    orderItem.setDiscount(BigDecimal.ZERO);
                    orderItem.setIsGift(false);
                    orderItem.setQuantity(BigDecimal.ONE);
                    orderItem.setPrice(BigDecimal.ZERO);
                    orderItem.setShippedQuantity(BigDecimal.ZERO);
                    orderItem.setReturnQuantity(BigDecimal.ZERO);
                    orderItem.setProductId(product.getId());
                    orderItem.setWeight(product.getWeight());
                    if (orderItem.getWeight() == null) {
                        orderItem.setWeight(BigDecimal.ZERO);
                    }
                    orderItems.add(orderItem);

        } else {
            for (OrderItem cartItem : orderItemService.getItemList(giftCard.getOrderId())) {

                    OrderItem orderItem = new OrderItem();
                    Product product = productService.selectByPrimaryKey(cartItem.getProductId());
                    order.setEnterpriseId(product.getEnterpriseId());

                    orderItem.setSubType(product.getSubType());
                    orderItem.setThumbnail(product.getThumbnail());
                    orderItem.setName(product.getName());
                    orderItem.setUnit(product.getUnit());
                    orderItem.setSn(product.getSn());
                    orderItem.setSpec(product.getSpec());
                    orderItem.setCost(product.getCost());
                    orderItem.setDiscount(BigDecimal.ZERO);
                    orderItem.setIsGift(false);
                    orderItem.setQuantity(cartItem.getQuantity());
                    orderItem.setPrice(BigDecimal.ZERO);
                    orderItem.setShippedQuantity(BigDecimal.ZERO);
                    orderItem.setReturnQuantity(BigDecimal.ZERO);
                    orderItem.setProductId(cartItem.getProductId());
                    orderItem.setWeight(product.getWeight());
                    if (orderItem.getWeight() == null) {
                        orderItem.setWeight(BigDecimal.ZERO);
                    }
                    orderItems.add(orderItem);

            }
        }
        order.setItemList(orderItems);

        return order;

    }

    @Transactional(rollbackFor = Exception.class)
    public Integer create(Order order) {

        Integer w = 0;
        Integer total = 0;
        order.setItemList(orderItemService.getItemList(order.getId()));

        String thumbnail = null;
        BigDecimal totalPrice = BigDecimal.ZERO;

        for (OrderItem orderItem:order.getItemList()) {
            // 套餐
           if (orderItem.getSubType().equals(1)) {

               for (int i=0;i<orderItem.getQuantity().intValue();i++) {
                   GiftCard giftCard = new GiftCard();
                   giftCard.setCreateDate(new Date());
                   giftCard.setEnterpriseId(order.getEnterpriseId());
                   giftCard.setMemberId(order.getMemberId());
                   giftCard.setName(orderItem.getName());
                   giftCard.setThumbnail(orderItem.getThumbnail());
                   giftCard.setPrice(orderItem.getPrice());
                   giftCard.setOrderId(order.getId());
                   giftCard.setProductId(orderItem.getProductId());
                   giftCard.setType(0);
                   giftCard.setStatus(0);
                   giftCardMapper.insertUseGeneratedKeys(giftCard);
               }

               total ++;
           } else {
               w = 1;
               totalPrice = totalPrice.add(orderItem.getAmount());
               thumbnail = orderItem.getThumbnail();
               total ++;
           }
        }

        if (w>0) {
            GiftCard giftCard = new GiftCard();
            giftCard.setCreateDate(new Date());
            giftCard.setEnterpriseId(order.getEnterpriseId());
            giftCard.setMemberId(order.getMemberId());
            giftCard.setName("订单礼品卡");
            giftCard.setThumbnail(thumbnail);
            giftCard.setPrice(totalPrice);
            giftCard.setOrderId(order.getId());
            giftCard.setProductId(null);
            giftCard.setType(1);
            giftCard.setStatus(0);
            giftCardMapper.insertUseGeneratedKeys(giftCard);
        }

        order.setOrderStatus(OrderStatusEnum.ORDER_STATUS_COMPLETE.getId());
        orderService.updateByPrimaryKeySelective(order);

        //对金币解冻
        if (order.getPoint()>0L) {
            pointService.decFreezePoint(order.getMemberId(),order.getPoint());
        }
        if (order.getRebate1().compareTo(BigDecimal.ZERO)>0) {
            pointService.decFreezePoint(order.getPromoterId1(),order.getRebate1().longValue());
        }
        if (order.getRebate2().compareTo(BigDecimal.ZERO)>0) {
            pointService.decFreezePoint(order.getPromoterId2(),order.getRebate2().longValue());
        }

        OrderLog orderLog = new OrderLog();
        orderLog.setType(OrderLogTypeEnum.ORDER_LOG_TYPE_COMPLETE.getId());
        orderLog.setContent("已转成礼卡");
        orderLog.setCreateDate(new Date());
        orderLog.setOrderId(order.getId());
        orderLogService.insertUseGeneratedKeys(orderLog);


        try {
            Member member = memberService.selectByPrimaryKey(order.getMemberId());

            Map<String,Object> content = new HashMap<>();
            content.put("title","您的订单已转成礼卡");
            content.put("itemList",order.getItemList());
            content.put("sn",order.getSn());
            content.put("id",order.getId());
            msgService.sendNotity(member,"msg-shipping","您的订单已转成礼卡", JSON.toJSONString(content),null);

        } catch (Exception e) {
            log.error(e.getMessage());
        }


        return total+w;
    }

    public List<OrderItem> getItemList(Long giftCardId) {
        GiftCard giftCard = super.selectByPrimaryKey(giftCardId);
        List<OrderItem> productList = new ArrayList<>();

        List<OrderItem> orderItemList = orderItemService.getItemList(giftCard.getOrderId());
        for (OrderItem orderItem:orderItemList) {
            if (orderItem.getSubType().equals(0)) {

                productList.add(orderItem);
            }
        }

        return productList;
    }

    public int updateUsingStatus(Long id) {
        Map<String,Object> params = new HashMap<>();
        params.put("id",id);
        return giftCardMapper.updateUsingStatus(params);
    }

}
